package com.ruoyi.web.controller.file;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.entity.SysFileInfo;
import com.ruoyi.system.service.ISysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JiaWang
 * @date 2023/3/7 11:23
 */
@Api(tags = "文件上传")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@Slf4j
@RequestMapping("/system/file")
public class SysFileInfoController extends BaseController {

    @Autowired
    private ISysFileInfoService sysFileInfoService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询附件
     */
    @ApiOperation(value = "查询附件")
    @GetMapping("/list")
    public AjaxResult list(@ApiParam(value = "附件参数", required = true) SysFileInfo fileInfo)
    {

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("table_name",fileInfo.getTableName());
        map.put("table_id",fileInfo.getTableId());
        List<SysFileInfo> list = sysFileInfoService.listByMap(map);
        return AjaxResult.success(list);
    }

    /**
     * 图片预览
     */
    @ApiOperation(value = "图片预览")
    @GetMapping("/getImgs")
    public void getImg2(HttpServletRequest request, HttpServletResponse response,String name)  throws IOException {
        if(null !=name && !name.equals("")){
            FileInputStream fis = null;
            OutputStream os = null;

            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                String server = serverConfig.getUrl();
                System.out.println(server+"777777777777777");

                //公共服务器目录地址
                fis = new FileInputStream(filePath+name);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/uploads")
    @Log(title = "文件上传" , businessType = BusinessType.INSERT)
    @ApiOperation(value = "文件上传")
    @ResponseBody
    public AjaxResult addSave(MultipartHttpServletRequest request, SysFileInfo fileInfo) throws IOException
    {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 获取文件集
        MultiValueMap<String,MultipartFile> map = request.getMultiFileMap();
        // 获取文件列表
        List<MultipartFile> list = map.get("file");
        List<SysFileInfo> infos = new ArrayList<SysFileInfo>();
        // 获取每个单独文件
        for (MultipartFile mFile : list) {
            SysFileInfo sfi = new SysFileInfo();
            // 附件名称
            //String fileName = mFile.getOriginalFilename();
            // 此处对每个文件进行操作 判断
            String fileName = FileUploadUtils.upload(filePath, mFile);
            fileInfo.setFilePath(filePath);
            fileInfo.setFileName(fileName);
            String fileFormat = StringUtils.substringAfterLast(fileName,".");
            fileInfo.setFileFormat(fileFormat);
            int i = sysFileInfoService.insertSysFileInfo(fileInfo);
            if(i>0){
                sfi = sysFileInfoService.getById(fileInfo.getId());
                infos.add(sfi);
            }
        }
        return AjaxResult.success(infos);
    }

    /**
     * 本地资源通用下载
     */
    @Log(title = "本地资源通用下载" , businessType = BusinessType.EXPORT)
    @ApiOperation(value = "本地资源通用下载")
    @GetMapping("/download")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        // 本地资源路径
        String localPath = RuoYiConfig.getUploadPath();
        // 数据库资源地址
        String downloadPath = localPath + resource;//StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    /**
     * 删除附件
     */
    @PreAuthorize("@ss.hasPermi('storehouse:area:remove')" )
    @Log(title = "删除附件" , businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除附件")
    @DeleteMapping("/{id}" )
    public AjaxResult remove(@ApiParam(value = "附件id", required = true) @PathVariable Long id) {
        //return toAjax(sysFileInfoService.removeByIds(Arrays.asList(id)) ? 1 : 0);
        return toAjax(sysFileInfoService.removeById(id) ? 1 : 0);
    }

    public static void main(String[] args) {
        String str = "/2023/03/09/mao_20230309151414A001.jpg";
        String ss = StringUtils.substringAfterLast(str,".");
        System.out.println(ss);
    }
}
